import { Form, Input, Select, Button, Table, Space, Modal } from 'antd';
import { useForm } from 'antd/es/form/Form';
import { ColumnsType } from 'antd/es/table';
import { Order, PageParams } from '@/types';
import { getOrderList, deleteOrder, exportOrder } from '@/api';
import { useEffect, useState } from 'react';
import { formatDate, formatMoney } from '@/utils';
import { message } from '@/utils/AntdGlobal';
import AuthButton from '@/components/AuthButton';
import CreateOrderList from '@/views/order/orderList/createOrderList';
import { useRef } from 'react';
import { IAction } from '@/types/modal';
import OrderDetail from '@/views/order/orderList/orderDetail';
import OrderMark from '@/views/order/orderList/orderMark';
import OrderRoute from '@/views/order/orderList/orderRoute';

export default function OrderList() {
  const [form] = useForm();
  const columns: ColumnsType<Order.OrderItem> = [
    {
      title: '订单编号',
      dataIndex: 'orderId',
      key: 'orderId',
      fixed: 'left'
    },
    {
      title: '城市名称',
      dataIndex: 'cityName',
      key: 'cityName'
    },
    {
      title: '下单地址',
      dataIndex: 'startAddress',
      key: 'startAddress',
      render(_, record) {
        return (
          <div>
            <p>开始地址: {record.startAddress}</p>
            <p>结束地址: {record.endAddress}</p>
          </div>
        );
      }
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render(time) {
        return formatDate(time);
      }
    },
    {
      title: '订单价格',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      render(price: string) {
        return formatMoney(price);
      }
    },
    {
      title: '订单状态',
      dataIndex: 'state',
      key: 'state',
      render(state: number) {
        return {
          1: '进行中',
          2: '已完成',
          3: '超时',
          4: '取消'
        }[state];
      }
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '司机名称',
      dataIndex: 'driverName',
      key: 'driverName'
    },
    {
      title: '操作',
      key: 'action', // 第一列是dataIndex，没有就是空的
      width: 300,
      render: (_, record) => {
        return (
          <Space>
            <Button type='primary' onClick={handleDetailClick(record.orderId)}>
              详情
            </Button>
            <Button type='primary' onClick={handleMark(record.orderId)}>
              打点
            </Button>
            <Button type='primary' onClick={handleOrderRoute(record.orderId)}>
              轨迹
            </Button>
            <Button type='primary' danger onClick={handleDelete(record._id)}>
              删除
            </Button>
          </Space>
        );
      }
    }
  ];
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });
  const [total, setTotal] = useState<number>(0);
  const [orderList, setOrderList] = useState<Order.OrderItem[]>();
  const markRef = useRef<{
    open: (id: string) => void;
  }>();
  const routeRef = useRef<{
    open: (id: string) => void;
  }>();
  const getOrderListData = async (params: PageParams) => {
    const formData = form.getFieldsValue();
    const data = await getOrderList({
      ...formData,
      pageNum: params.pageNum,
      pageSize: params.pageSize || pagination.pageSize
    });
    setOrderList(data.list);
    setTotal(data.page.total);
  };
  useEffect(() => {
    getOrderListData({
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    });
  }, [pagination.current, pagination.pageSize]);

  const handleSearch = () => {
    getOrderListData({
      pageNum: 1
    });
  };
  const handleRest = () => {
    form.resetFields();
    getOrderListData({
      pageNum: 1
    });
  };
  const handleTableChange = (pageNum: number) => {
    setPagination({
      ...pagination,
      current: pageNum
    });
  };
  const handleDelete = (_id: string) => () => {
    Modal.confirm({
      title: '删除确认',
      content: <span>你确定要删除该订单吗?</span>,
      onOk: async () => {
        await deleteOrder({ _id });
        message.success('删除成功');
        getOrderListData({
          pageNum: pagination.current
        });
      }
    });
  };
  // 创建订单
  const handleCreate = () => {
    createOrderRef.current?.open('create');
  };
  const detailRef = useRef<{
    open: (orderId: string) => void;
  }>();
  const createOrderRef = useRef<{
    open: (type: IAction) => void;
    update: () => void;
  }>();

  const handleDetailClick = (orderId: string) => () => {
    detailRef.current?.open(orderId);
  };

  const handleMark = (id: string) => () => {
    markRef.current?.open(id);
  };

  const handleOrderRoute = (id: string) => () => {
    routeRef.current?.open(id);
  };

  const handleExport = async () => {
    const data = await exportOrder(form.getFieldsValue());
    console.log(data);
  };
  return (
    <div className='orderList'>
      <Form className='search-form' layout='inline' form={form}>
        <Form.Item name='orderId' label='订单ID'>
          <Input placeholder='请输入订单ID'></Input>
        </Form.Item>
        <Form.Item name='userName' label='用户名称'>
          <Input placeholder='请输入用户名称'></Input>
        </Form.Item>
        <Form.Item name='state' label='订单状态'>
          <Select style={{ width: 180 }} placeholder='请选择订单状态'>
            <Select.Option value={1}>进行中</Select.Option>
            <Select.Option value={2}>已完成</Select.Option>
            <Select.Option value={3}>超时</Select.Option>
            <Select.Option value={4}>取消</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type='primary' className='mr10' onClick={handleSearch}>
            搜索
          </Button>
          <Button type='primary' danger onClick={handleRest}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>用户列表</div>
          <div className='active'>
            <AuthButton onClick={handleCreate} type='primary'>
              新增
            </AuthButton>
            <Button type='primary' onClick={handleExport}>
              导出
            </Button>
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={orderList}
          bordered
          scroll={{ x: 2000 }}
          rowKey='_id'
          pagination={{
            position: ['bottomRight'],
            current: pagination.current,
            pageSize: pagination.pageSize,
            total,
            showTotal: total => {
              return `总共: ${total}条`;
            },
            onChange: handleTableChange
          }}
        />
      </div>
      <CreateOrderList
        mRef={createOrderRef}
        update={() => {
          getOrderListData({
            pageNum: pagination.current
          });
        }}
      ></CreateOrderList>
      <OrderDetail mRef={detailRef}></OrderDetail>
      <OrderMark mRef={markRef}></OrderMark>
      <OrderRoute mRef={routeRef}></OrderRoute>
    </div>
  );
}
